from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

from ui.Frm_Update import Ui_Frm_Update
import threading
import os
import requests
import json
import time
downloadstatus = 0
downloadspeed = 0
closeMe = False

def downloadISpider(url):
    global downloadstatus,downloadspeed,closeMe

    r = requests.get(url,stream=True)

    if r.headers['Content-Type'] == 'application/octet-stream':
        max = int(r.headers['Content-Length'])
        change = 102400 / max
        with open('ISpider.exe','wb') as f:
            time1 = time.time()
            count = 0
            count_temp = 0
            for chunk in r.iter_content(chunk_size=512):
                f.write(chunk)
                count += len(chunk)
                if time.time() - time1 > 2:
                    downloadstatus = count / max * 100
                    speed = (count - count_temp) / 1024 / 1024 / 2
                    count_temp = count
                    downloadspeed = speed
                    time1 = time.time()
    downloadstatus=100
    downloadspeed = 0
    closeMe = True
class Uipy_Frm_Update(QWidget,Ui_Frm_Update):
    def __init__(self,parent=None):
        super(Uipy_Frm_Update, self).__init__(parent)
        self.setupUi(self)
        self.isClose = False

        self.pB_Status.setValue(0)
        self.pB_Download.clicked.connect(self.down)
        self.thead = threading.Timer(0,self.pB_Value)
        self.thead.start()

    def down(self):
        try:
            if os.path.exists('ISpider.exe'):
                os.remove('ISpider.exe')

            if os.path.exists('config.json'):
                os.remove('config.json')

            configUrl = 'https://gitee.com/ruxia-tjy/ispider/raw/master/config.json'

            r = requests.get(configUrl)
            if r.status_code == 200:
                with open('config.json','w',encoding='utf-8') as f:
                    f.write(r.text)
            else:
                QMessageBox.information(self,'提示',f'从服务器获取配置文件错误，返回值{r.status_code}')
            j = json.loads(r.text)
            newUrl = j['最新版本下载地址']

            whaturl = 'https://gitee.com/ruxia-tjy/ispider/raw/master/%E6%9B%B4%E6%96%B0%E6%97%A5%E5%BF%97.txt'
            r = requests.get(whaturl)
            if r.status_code==200:
                with open('更新日志.txt','w',encoding='utf-8') as f:
                    f.write(r.text)

            th = threading.Timer(0,downloadISpider,(newUrl,))
            th.start()
            th.join()
            self.pB_Download.setEnabled(False)
        except Exception as e:
            QMessageBox.information(self,'提示',f'更新错误！\n'
                                              f'请尝试以下操作：\n'
                                              f'1.关闭正在运行的ISpider\n'
                                              f'2.删除ISpider.exe,config.json文件\n'
                                              f'或者联系作者：错误信息：{e}')

    def pB_Value(self):
        while True:
            if self.isClose:
                break
            self.pB_Status.setValue(downloadstatus)
            self.lbl_speed.setText('{:.2f} M/s'.format(downloadspeed))
            if closeMe:
                self.close()

    def closeEvent(self, QCloseEvent):
        self.isClose = True
